package com.jams.goodox.activity.qa;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.BuildConfig;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.common.SimpleHtmlActivity;
import com.jams.goodox.activity.mine.download.DownloadBean;
import com.jams.goodox.activity.mine.image.Util;
import com.jams.goodox.activity.qa.entity.CourseComment;
import com.jams.goodox.activity.qa.entity.Teacher;
import com.jams.goodox.activity.qa.teacher.TeacherDetailActivity;
import com.jams.goodox.adapter.lfadapter.CommonRecycleViewAdapter;
import com.jams.goodox.adapter.lfadapter.LFRecyclerViewHolder;
import com.jams.goodox.db.DBManager;
import com.jams.goodox.entity.PinLun;
import com.jams.goodox.listen.CustomShareListener;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TimeUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.github.lizhangqu.coreprogress.ProgressHelper;
import io.github.lizhangqu.coreprogress.ProgressListener;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by HP on 2018/5/13.
 *
 * 课堂详情
 * api/course/detail
 */

public class ClassLearningActivity extends BaseActivity implements View.OnClickListener,
        OnItemClickListener,LFRecyclerView.LFRecyclerViewListener,
        LFRecyclerView.LFRecyclerViewScrollChange {

    private static final String TAG = "ClassLearningActivity";

    @Bind(R.id.pull_refresh_list)
    LFRecyclerView recycleView;

    View headerView;

    private CommonRecycleViewAdapter pAdapter;
    private List<CourseComment> dataList = new ArrayList<>();

    SimpleDraweeView headImage;
    TextView title;
    TextView name;
    ImageView addComments;
    TextView tv_counts;

    ImageView thumbsUp;
    ImageView comment;
    ImageView download;

    ImageView play_btn;
    ImageView previous;
    ImageView next;
    TextView audiotext;
    TextView allaudio;

    @Bind(R.id.trail)
    TextView trail;
    @Bind(R.id.buyCourse)
    TextView buyCourse;
    @Bind(R.id.relative_button)
    RelativeLayout relative_button;

    SeekBar progressBarHorizontal;
    TextView startTime;
    TextView timeLength;

    private Intent intent;

    private int courseId;
    private String radioLink ;
    private String titleTx;
    private String imagePath;
    private String nickName;
    private int seriesId = -1;//

    File outFile;

    private static final int UPDATE = 0;
    private int pageNum = 1;
    private int pageSize = 10;
    private boolean status = false;//判断加载成功还是失败
    private boolean isRefresh = true;

    private SimpleDateFormat time = new SimpleDateFormat("mm:ss");
    private boolean tag1 = false;
    private boolean tag2 = false;

    public MediaPlayer mediaPlayer;
    public boolean tag = false;
    String content;//文字翻译
    private  boolean isTrail = false;
    private int trailTime = 0;//试听时间

    private boolean canShare = false;//是否可以分享

    Handler handler=new Handler()  {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    misLoading();
                    break;
                case 1:
                    misLoading();
                    showShackBar("下载完成");
                    DownloadBean downloadBean = new DownloadBean();
                    downloadBean.setTitle(titleTx);
                    downloadBean.setPic(imagePath);
                    downloadBean.setName(nickName);
                    downloadBean.setUrl(outFile.getAbsolutePath());
                    Log.d(TAG, "downloadBean = " + downloadBean);
                    DBManager.getInstance(ClassLearningActivity.this).insertOneItem(downloadBean);
                    break;
                case 2:
                    Log.d(TAG,"-------初始化服务--------");
                    Log.d(TAG,"-------enable事件--------");
                    setMedia();

                    if(canPlay){
                        play_btn.setEnabled(true);
                        previous.setEnabled(true);
                        next.setEnabled(true);
                        download.setEnabled(true);
                        progressBarHorizontal.setEnabled(true);

                    }
                    break;

                case 3:
                    misLoading();
                    if (isRefresh){
                        recycleView.stopRefresh(status);
                        pAdapter.notifyDataSetChanged();
                    }else {
                        recycleView.stopLoadMore();
                        pAdapter.notifyDataSetChanged();
                    }

                    tv_counts.setText("留言精选(" + dataList.size()+")");
                    break;

                case 9:
                    trailTime--;
                    if(trailTime > 0){
                        trail.setText("倒计时 : "  + trailTime + "s");
                        handler.sendEmptyMessageDelayed(9,1000);
                    }else {
                        handler.removeMessages(9);
                        trail.setText("免费试听");
                        ToastUtil.show("试听结束");
                        mediaPlayer.seekTo(0);//回到起始位置
                        play_btn.performClick();
                        trail.setEnabled(true);
                    }

                    break;
            }
        }
    };

    private File downloadFile;

    private boolean canPlay;//是否可以播放
    private double price = 0;
    private boolean isFromSerious = false;


    // IWXAPI 是第三方app和微信通信的openapi接口
    WXWebpageObject webpage;
    WXMediaMessage msg;
    SendMessageToWX.Req req;


    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(mediaPlayer.getDuration() <= mediaPlayer.getCurrentPosition()){
                startTime.setText(time.format(mediaPlayer.getDuration()));
            }else {
                startTime.setText(time.format(mediaPlayer.getCurrentPosition()));
            }
            progressBarHorizontal.setProgress(mediaPlayer.getCurrentPosition());
            //progressBarHorizontal.setMax(mediaPlayer.getDuration());
            //timeLength.setText(time.format(mediaPlayer.getDuration()));
            handler.postDelayed(runnable, 200);

        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.activity_classlearning;
    }

    /**
     * 创建文本消息对象。
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        Log.d("TTTTTT11","titleTx = " + titleTx);
        TextObject textObject = new TextObject();
        textObject.text = TextUtils.isEmpty(titleTx) ? "好氧课堂" : titleTx + "  " + BuildConfig.BASE_URL +
                "page/course/list?id=" + courseId;
        textObject.title = TextUtils.isEmpty(titleTx) ? "好氧课堂" : titleTx ;;
        textObject.actionUrl = BuildConfig.BASE_URL +
                "page/course/list?id=" + courseId;

//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//        textObject.thumbData = baos.toByteArray();

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        textObject.thumbData = Util.bmpToByteArray(thumbBmp, true);

        return textObject;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Override
    protected void init() {
        canShare = getIntent().getBooleanExtra("canShare",false);
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部
        if(canShare){
            StyleUtil.titleBothIconListener(this, "课堂学习", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    },

                    R.mipmap.icon_share_btn, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            showSharePop(new CustomShareListener() {
                                @Override
                                public void onShareCallBack(int type) {

                                    switch (type){
                                        case 1:
                                            Log.d("TTTTTT11","titleTx = " + titleTx);
                                            webpage = new WXWebpageObject();
                                            webpage.webpageUrl = BuildConfig.BASE_URL +
                                                "page/course/list?id=" + courseId;
                                            msg = new WXMediaMessage(webpage);
                                            msg.title = TextUtils.isEmpty(titleTx) ? "好氧课堂" : titleTx ;
                                            msg.description = /*TextUtils.isEmpty(titleTx) ? "好氧课堂" : titleTx*/ " " ;


//                                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.login_logo_icon);
//                                            msg.setThumbImage(bitmap);

                                            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
                                            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                                            bmp.recycle();
                                            msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

                                            req = new SendMessageToWX.Req();
                                            req.transaction = buildTransaction("webpage");
                                            req.message = msg;
                                            req.scene = SendMessageToWX.Req.WXSceneSession;
                                            api.sendReq(req);

                                            break;
                                        case 2:
                                            Log.d("TTTTTT11","titleTx = " + titleTx);
                                            webpage = new WXWebpageObject();
                                            webpage.webpageUrl = BuildConfig.BASE_URL +
                                                    "page/course/list?id=" + courseId;
                                            msg = new WXMediaMessage(webpage);
                                            msg.title = TextUtils.isEmpty(titleTx) ? "好氧课堂" : titleTx ;
                                            msg.description = /*TextUtils.isEmpty(titleTx) ? "好氧课堂" : titleTx*/ " " ;

//                                            Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(),R.mipmap.login_logo_icon);
//                                            msg.setThumbImage(bitmap2);

                                            Bitmap bmp2 = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
                                            Bitmap bitmap2 = Bitmap.createScaledBitmap(bmp2, THUMB_SIZE, THUMB_SIZE, true);
                                            bmp2.recycle();
                                            msg.thumbData = Util.bmpToByteArray(bitmap2, true);


                                            req = new SendMessageToWX.Req();
                                            req.transaction = buildTransaction("webpage");
                                            req.message = msg;
                                            req.scene = SendMessageToWX.Req.WXSceneTimeline;
                                            api.sendReq(req);
                                            break;

                                        case 3:
                                            WbShareHandler shareHandler = new WbShareHandler(ClassLearningActivity.this);
                                            shareHandler.registerApp();
                                            shareHandler.setProgressColor(getResources().getColor(R.color.main_background));

                                            WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                                            weiboMessage.textObject = getTextObj();

                                            shareHandler.shareMessage(weiboMessage, true);

//                                        WeiboPageUtils.getInstance(SimpleHtmlActivity.this,authInfo).shareToWeibo("哈哈哈哈哈",useWeb);
                                            break;

                                        case 4:
                                            ClipboardManager cm = (ClipboardManager)
                                                    getSystemService(Context.CLIPBOARD_SERVICE);
                                            // 将文本内容放到系统剪贴板里。
                                            cm.setText(BuildConfig.BASE_URL +
                                                    "page/course/list?id=" + courseId);
                                            ToastUtil.show("复制成功");
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            });
                        }
                    });
        }else {
            StyleUtil.titleBackKey(this, "课堂学习");
        }


//        setUpShare();


        courseId = getIntent().getIntExtra("courseId",-1);
        imagePath = getIntent().getStringExtra("imagePath");
        nickName = getIntent().getStringExtra("nickName");
        isFromSerious = getIntent().getBooleanExtra("isFromSerious",false);

        headerView = getLayoutInflater().inflate(R.layout.header_classlearning,null);
        headImage = (SimpleDraweeView) headerView.findViewById(R.id.headImage);
        headImage.setImageURI(Uri.parse(imagePath));
//        Glide.with(this).load(imagePath)
//                .placeholder(R.drawable.loading) //占位符 也就是加载中的图片，可放个gif
//                .error(R.mipmap.morentouxiang60) //失败图片
//                .bitmapTransform(new GlideCircleTransform(this)).crossFade(1000).into(headImage);

        title = (TextView) headerView.findViewById(R.id.title);
        name = (TextView) headerView.findViewById(R.id.name);
        name.setText(nickName);

        addComments = (ImageView) headerView.findViewById(R.id.addComments);
        addComments.setOnClickListener(this);
        tv_counts = (TextView) headerView.findViewById(R.id.tv_counts);

        thumbsUp = (ImageView) headerView.findViewById(R.id.thumbsUp);
        comment = (ImageView) headerView.findViewById(R.id.comment);
        download = (ImageView) headerView.findViewById(R.id.download);
        play_btn = (ImageView) headerView.findViewById(R.id.play_btn);
        play_btn.setOnClickListener(this);
        previous = (ImageView) headerView.findViewById(R.id.previous);
        previous.setOnClickListener(this);
        next = (ImageView) headerView.findViewById(R.id.next);
        next.setOnClickListener(this);

        audiotext = (TextView) headerView.findViewById(R.id.audiotext);
        audiotext.setOnClickListener(this);
        allaudio = (TextView) headerView.findViewById(R.id.allaudio);
        allaudio.setOnClickListener(this);
        if(isFromSerious){
            allaudio.setVisibility(View.GONE);
        }else {
            allaudio.setVisibility(View.VISIBLE);
        }

        progressBarHorizontal = (SeekBar) headerView.findViewById(R.id.progressBarHorizontal);
        startTime = (TextView) headerView.findViewById(R.id.startTime);
        timeLength = (TextView) headerView.findViewById(R.id.timeLength);

        //bindServiceConnection();
        play_btn.setEnabled(false);
        previous.setEnabled(false);
        next.setEnabled(false);
        download.setEnabled(false);
        progressBarHorizontal.setEnabled(false);

//        getCourseDetail();

        recycleView.setLoadMore(true);
        recycleView.setRefresh(false);
        //recycleView.setNoDateShow();
        recycleView.setAutoLoadMore(false);
        recycleView.setOnItemClickListener(this);
        recycleView.setLFRecyclerViewListener(this);
        recycleView.setScrollChangeListener(this);
        recycleView.setFootText("加载更多");
//        recycleView.setItemAnimator(new DefaultItemAnimator());

        pAdapter = new CommonRecycleViewAdapter(recycleView, dataList, R.layout.addcomment_item) {
            @Override
            public void bindConvert(LFRecyclerViewHolder holder, int position, Object item, boolean isScrolling) {

                CourseComment pinLun = (CourseComment) item;
                holder.setText(R.id.nickName, pinLun.getNickName());
                holder.setText(R.id.content,pinLun.getContent());
                holder.setText(R.id.createTime, TimeUtils.getDateToString(pinLun.getCreateTime()));
                holder.loadImage(R.id.imageView, pinLun.getImgPath());
            }
        };

        //pAdapter.setHeaderView();
        recycleView.setHeaderView(headerView);
        recycleView.setAdapter(pAdapter);

        getCourseDetail();
    }


//    private void setUpShare() {
//        mShareListener = new CustomShareListener<ClassLearningActivity>(ClassLearningActivity.this);
//
//        /*增加自定义按钮的分享面板*/
//        mShareAction = new ShareAction(this).setDisplayList(
//                SHARE_MEDIA.WEIXIN,
//                SHARE_MEDIA.WEIXIN_CIRCLE,
//                SHARE_MEDIA.SINA,
//                SHARE_MEDIA.QQ,
//                SHARE_MEDIA.QZONE)
//                .setShareboardclickCallback(new ShareBoardlistener() {
//                    @Override
//                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
//                        UMWeb web = new UMWeb(BuildConfig.BASE_URL +
//                                "page/course/list?id=" + courseId
//                        );
//                        web.setTitle(/*"来自分享面板标题"*/"课堂学习");
//                        web.setDescription("来自分享面板内容");
//                        web.setThumb(new UMImage(ClassLearningActivity.this, R.mipmap.ic_launcher));
//                        new ShareAction(ClassLearningActivity.this).withMedia(web)
//                                .setPlatform(share_media)
//                                .setCallback(mShareListener)
//                                .share();
//                    }
//                });
//
//    }


    private void setMedia() {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(radioLink);
            mediaPlayer.prepare();
            mediaPlayer.setLooping(false);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                timeLength.setText(time.format(mediaPlayer.getDuration()));
            }
        });


        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //ToastUtil.show("播放结束");
                Log.d(TAG,  "播放结束" );
                play_btn.setImageResource(R.mipmap.bofang_yinpin);
                //musicService.stop();
                //musicService.mediaPlayer.stop();
            }
        });

        progressBarHorizontal.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser == true) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @OnClick({  R.id.trail,R.id.buyCourse,R.id.relative_button })
    public void onClick2(View view) {
        if (Utils.isFastDoubleClick())
            return;
        switch (view.getId()) {
//            case R.id.courseDetail:
//                intent = new Intent(ClassLearningActivity.this,CourseDetailActivity.class);
//                intent.putExtra("courseId",courseId);
//                startActivity(intent);
//                break;
//            case R.id.thumbsUp:
//                if(SePref.isLogin()){
//                    if(canPlay){
//                        thumbsUp();
//                    }else {
//                        ToastUtil.show("您尚未购买此课程");
//                    }
//                } else {
//                    ToastUtil.show("您尚未登录");
//                }
//                break;
//            case R.id.comment:
//                if(SePref.isLogin()) {
//                    if(canPlay){
//                        intent = new Intent(ClassLearningActivity.this, AddCommentActivity.class);
//                        intent.putExtra("courseId", courseId);
//                        startActivity(intent);
//                    }else {
//                        ToastUtil.show("您尚未购买此课程");
//                    }
//                }else {
//                    ToastUtil.show("您尚未登录");
//                }
//                break;
//            case R.id.download:
//                if(SePref.isLogin()) {
//                    if(canPlay){
//                        okHttpDownLoad(radioLink);
//                    }else {
//                        ToastUtil.show("您尚未购买此课程");
//                    }
//                }else {
//                    ToastUtil.show("您尚未登录");
//                }
//
//                break;
//            case R.id.play_btn:
//                if(TextUtils.isEmpty(radioLink)){
//                    ToastUtil.show("获取音频文件失败");
//                    return;
//                }
//                if (mediaPlayer != null) {
//                    progressBarHorizontal.setProgress(mediaPlayer.getCurrentPosition());
//                    progressBarHorizontal.setMax(mediaPlayer.getDuration());
//                }
//                //  由tag的变换来控制事件的调用
//                if (tag != true) {
//                    play_btn.setImageResource(R.mipmap.zanting_yinpin);
//                    //btnPlayOrPause.setText("PAUSE");
//                    //musicStatus.setText("Playing");
//                    playOrPause();
//                    tag = true;
//
//                } else {
//                    play_btn.setImageResource(R.mipmap.bofang_yinpin);
//                    //btnPlayOrPause.setText("PLAY");
//                    //musicStatus.setText("Paused");
//                    playOrPause();
//                    tag = false;
//                }
//                if (tag2 == false) {
//                    handler.post(runnable);
//                    tag2 = true;
//                }
//
//                break;
//
//            case R.id.previous:
//                seekBack();
//                break;
//
//            case R.id.next:
//                seekForword();
//                break;

            case R.id.buyCourse:
            case R.id.relative_button:
                if(SePref.getCoinCount() < price){
                    ToastUtil.show("当前氧币不足，请前往个人中心充值");
                }else {
                    new MaterialDialog.Builder(this).title("好氧提示")
                            .content("购买此课程将消耗您" + price + "氧币")
                            .positiveColorRes(R.color.font_color_blue).positiveText("确定")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                    buyOrder();

                                }
                            }).negativeColorRes(R.color.font_color_black).negativeText("取消")
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                }
                            }).show();
                }

                break;

            case R.id.trail:
                //试听15秒
                isTrail = true;
                trailTime = 15;//
                trail.setEnabled(false);
                play_btn.performClick();

                if(mediaPlayer != null && isTrail && mediaPlayer.getDuration() > 15000){
                    //如果小于15秒 就不用倒计时
                    handler.sendEmptyMessageDelayed(9,1000);
                }

                break;
            default:
                break;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.play_btn:
                if(TextUtils.isEmpty(radioLink)){
                    ToastUtil.show("获取音频文件失败");
                    return;
                }
                if (mediaPlayer != null) {
                    progressBarHorizontal.setProgress(mediaPlayer.getCurrentPosition());
                    progressBarHorizontal.setMax(mediaPlayer.getDuration());
                }
                //  由tag的变换来控制事件的调用
                if (tag != true) {
                    play_btn.setImageResource(R.mipmap.zanting_yinpin);
                    //btnPlayOrPause.setText("PAUSE");
                    //musicStatus.setText("Playing");
                    playOrPause();
                    tag = true;

                } else {
                    play_btn.setImageResource(R.mipmap.bofang_yinpin);
                    //btnPlayOrPause.setText("PLAY");
                    //musicStatus.setText("Paused");
                    playOrPause();
                    tag = false;
                }
                if (tag2 == false) {
                    handler.post(runnable);
                    tag2 = true;
                }

                break;

            case R.id.previous:
                seekBack();
                break;

            case R.id.next:
                seekForword();
                break;

            case R.id.allaudio:
                //所有音频
                intent = new Intent(ClassLearningActivity.this,AllCourseVideoActivity.class);
                intent.putExtra("seriesId",seriesId);
                intent.putExtra("courseId",courseId);
                startActivity(intent);
                break;

            case R.id.audiotext:
                intent = new Intent(ClassLearningActivity.this,CourseTXTActivity.class);
                intent.putExtra("contentTx",content);
                intent.putExtra("titleTx",titleTx);
                startActivity(intent);
                break;

            case R.id.addComments:
                if(SePref.isLogin()){
                    intent = new Intent(ClassLearningActivity.this, AddCommentActivity.class);
                    intent.putExtra("courseId", courseId);
                    startActivity(intent);
                }else {
                    ToastUtil.show("请登录后评论！");
                }
                break;

            default:
                break;

        }
    }



    //创建订单接口
    private void buyOrder() {
        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("courseId:" + courseId)
                .append(",memberId:" + SePref.getId());

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).buyOrder(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);
                    JSONObject jsonObject = new JSONObject(data);
                    if(200 == jsonObject.getInt("code")){
                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));

                        boolean result = object.getBoolean("result");
                        if(result){
                            int id = object.getInt("id");
                            payOrder(id);
                        }

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });

    }

    //课程购买
    private void payOrder(int id) {
        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("courseOrderId:" + id)
                .append(",coinCount:" + price);

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).payOrder(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);
                    JSONObject jsonObject = new JSONObject(data);
                    if(200 == jsonObject.getInt("code") && "true".equals(jsonObject.getString("responseData"))){

                        //ToastUtil.show("购买成功");
                        showShackBar("购买成功");
                        relative_button.setVisibility(View.GONE);
                        canPlay = true;
                        handler.sendEmptyMessageDelayed(2,100);

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });

    }

    private void okHttpDownLoad(final String url) {
        //client
        OkHttpClient okHttpClient = new OkHttpClient();
        //request builder
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        builder.get();
        //call
        okhttp3.Call call= okHttpClient.newCall(builder.build());
        //enqueue

        showLoading("正在下载...");
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                Log.d(TAG, "=============onFailure===============");
                e.printStackTrace();
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                Log.d(TAG, "=============onResponse===============");
                Log.d(TAG, "request headers:" + response.request().headers());
                Log.d(TAG, "response headers:" + response.headers());

                //your original response body
                ResponseBody body = (ResponseBody) response.body();
                //wrap the original response body with progress
                ResponseBody responseBody = ProgressHelper.withProgress(body, new ProgressListener() {
                    //if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
                    @Override
                    public void onProgressStart(long totalBytes) {
                        super.onProgressStart(totalBytes);
                        Log.d(TAG, "totalBytes:" + totalBytes);
                    }

                    @Override
                    public void onProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
                        Log.d(TAG, "percent:" + percent);
                    }

                    //if you don't need this method, don't override this methd. It isn't an abstract method, just an empty method.
                    @Override
                    public void onProgressFinish() {
                        super.onProgressFinish();
                        Log.d(TAG, "onProgressFinish:" );
                        handler.sendEmptyMessage(1);
                    }
                });
                //read the body to file
                BufferedSource source = responseBody.source();
                String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/youyang/mp3";
                outFile = new File(savePath,getFileNameWithSuffix(url));
                outFile.delete();
                outFile.getParentFile().mkdirs();
                outFile.createNewFile();
                BufferedSink sink = Okio.buffer(Okio.sink(outFile));
                source.readAll(sink);
                sink.flush();
                source.close();
            }
        });
    }


    public String getFileNameWithSuffix(String pathandname) {
        int start = pathandname.lastIndexOf("/");
        if (start != -1 ) {
            return pathandname.substring(start + 1);
        } else {
            return null;
        }
    }

    //点赞接口
    private void thumbsUp() {

        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("courseId:" + courseId)
                .append(",memberId:" + SePref.getId());

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).thumbUp(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);
                    JSONObject jsonObject = new JSONObject(data);
                    if(200 == jsonObject.getInt("code")){
                        ToastUtil.show("点赞成功");
                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }



    private void getCourseDetail(){
        if(-1 == courseId){
            ToastUtil.show("课程id为空");
            return;
        }
        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("courseId:" + courseId)
                .append(",memberId:" + SePref.getId());

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading("正在加载...");
        Call<ResponseBody> example = createCallService(LoginService.class).courseDetail(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                handler.sendEmptyMessageDelayed(0,1500);
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);
                    JSONObject jsonObject = new JSONObject(data);
                    if(200 == jsonObject.getInt("code")){
                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));
                        radioLink = object.getString("radioLink");

                        //MusicService.url = radioLink;
                        content = object.getString("content");

                        String descr = object.getString("descr");
                        titleTx = object.getString("title");
                        title.setText(titleTx);

                        price = object.getDouble("price");
                        int isFree = object.getInt("isFree");//0 收费 1免费
                        double timeLength = object.getDouble("timeLength");
                        int clickNum = object.getInt("clickNum");
                        String uuid = object.getString("uuid");
                        int translateState = object.getInt("translateState");
                        int status = object.getInt("status");
                        int auditStatus = object.getInt("auditStatus");
                        String createTime = object.getString("createTime");
                        int createId = object.getInt("createId");
                        String updateTime = object.getString("updateTime");
                        int updateId = object.getInt("updateId");
                        int memberId = object.getInt("memberId");

                        if(object.has("seriesId")){
                            seriesId = object.getInt("seriesId");
                        }

                        boolean isBuy = false;
                        if(object.has("isBuy")){
                            isBuy = object.getBoolean("isBuy");
                        }

                        //已经购买或者免费课程,或者 教师自己录制的课程 不显示
                        if(isBuy || (price <= 0) || memberId == SePref.getId()){
                            relative_button.setVisibility(View.GONE);
//                            contentTx.setText(content);
                            canPlay = true;
                        }else {
                            canPlay = false;
                            relative_button.setVisibility(View.VISIBLE);
                            buyCourse.setText("购买课程(¥" + price +  ")");
//                            contentTx.setText("购买后查看...");
                        }

                        handler.sendEmptyMessageDelayed(2,100);
                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                handler.sendEmptyMessageDelayed(0,1500);
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }


    //    获取评论列表
    private void listComment() {
        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("courseId:" + courseId)
                .append(",pageNum:" + pageNum)
                .append(",pageSize:" + pageSize);

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).listComment(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String data = response.body().string();
                    Log.d(TAG, "listComment = " + data);
                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        status = true;
                        if(isRefresh){
                            dataList.clear();
                        }

                        JSONArray jsonArray = new JSONArray(jsonObject.getString("responseData"));
                        if(null == jsonArray || jsonArray.length() <= 0){
                            return;
                        }

                        for (int i = 0; i < jsonArray.length(); i ++){
                            JSONObject object = jsonArray.getJSONObject(i);
                            CourseComment courseComment = new CourseComment();
                            courseComment.setContent(object.getString("content"));
                            courseComment.setCreateTime(object.getLong("createTime"));
                            courseComment.setImgPath(object.getString("imgPath"));
                            courseComment.setNickName(object.getString("nickName"));

                            dataList.add(courseComment);
                        }

                        pAdapter.notifyDataSetChanged();

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });

        handler.sendEmptyMessageDelayed(3,200);
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume = " );
        //getCourseDetail();
        isRefresh = true;
        isTrail = false;
        pageNum = 1;
        listComment();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause = " );
//        stop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy = " );
        handler.removeCallbacks(runnable);
        handler.removeCallbacksAndMessages(null);
        release();

    }

    public void playOrPause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        } else {
            mediaPlayer.start();
        }
    }

    public void seekBack(){
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()){
                int current = mediaPlayer.getCurrentPosition();
                if(current < 5000){
                    mediaPlayer.seekTo(0);
                }else {
                    mediaPlayer.seekTo(current - 5000);
                }
            }
        }
    }


    public void seekForword(){
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()){
                int current = mediaPlayer.getCurrentPosition();
                if(current + 5000 > mediaPlayer.getDuration()){
                    mediaPlayer.seekTo(mediaPlayer.getDuration());
                }else {
                    mediaPlayer.seekTo(current + 5000);
                }
            }
        }
    }


    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            /*try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
                mediaPlayer.seekTo(0);
            } catch (Exception e) {
                e.printStackTrace();
            }*/
        }
    }

    public void release(){
        if(mediaPlayer != null){
            mediaPlayer.release();

        }
    }

    @Override
    public void onRecyclerViewScrollChange(View view, int i, int i1) {

    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        pageNum ++;
        isRefresh = false;
        listComment();
    }

    @Override
    public void onClick(int position) {

    }

    @Override
    public void onLongClick(int po) {

    }

}
